<template>
  <el-dialog :title="title" :model-value="modelValue" @update:model-value="(value) => emit('update:modelValue', value)" width="800px" append-to-body @close="handleClose">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属产品" prop="productId">
            <el-select v-model="formData.productId" placeholder="请选择所属产品" style="width: 100%" @change="handleProductChange">
              <el-option
                v-for="product in productList"
                :key="product.id"
                :label="product.name"
                :value="product.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="协议名称" prop="protocolName">
            <el-input v-model="formData.protocolName" placeholder="请输入协议名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="协议版本号" prop="protocolVersion">
            <el-input v-model="formData.protocolVersion" placeholder="请输入协议版本号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="通信协议类型" prop="communicationType">
            <el-select v-model="formData.communicationType" placeholder="请选择通信协议类型" style="width: 100%">
              <el-option label="HTTP" value="HTTP" />
              <el-option label="MQTT" value="MQTT" />
              <el-option label="TCP" value="TCP" />
              <el-option label="UDP" value="UDP" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="编码格式" prop="encoding">
            <el-select v-model="formData.encoding" placeholder="请选择编码格式" style="width: 100%">
              <el-option label="UTF-8" value="UTF-8" />
              <el-option label="GBK" value="GBK" />
              <el-option label="ASCII" value="ASCII" />
              <el-option label="Unicode" value="Unicode" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio label="1">启用</el-radio>
              <el-radio label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
       <el-row>
         <el-col :span="24">
           <el-form-item label="备注" prop="remark">
             <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注" />
           </el-form-item>
         </el-col>
       </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'

import type { ProtocolFormData } from '@/api/IOT/protocolManage/protocolList/types'
import type { ProductInfo } from '@/api/IOT/protocolManage/productManage/types'

// 本地虚拟延迟（随机不超过1.5s）
const delayRandom = (min = 300, max = 1500) => new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * (max - min + 1)) + min))

// Props
interface Props {
  modelValue: boolean
  title: string
  protocolData?: any
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: '新增协议',
  protocolData: null
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': [data: any]
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const loading = ref(false)
const productList = ref<ProductInfo[]>([])

// 表单数据
const formData = reactive<ProtocolFormData>({
  productId: undefined,
  productName: '',
  protocolName: '',
  protocolVersion: '',
  communicationType: undefined,
  encoding: undefined,
  status: undefined,
  remark: ''
})

// 表单验证规则
const rules = reactive({
  productId: [
    { required: true, message: '请选择所属产品', trigger: 'change' }
  ],
  protocolName: [
    { required: true, message: '请输入协议名称', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  protocolVersion: [
    { required: true, message: '请输入协议版本号', trigger: 'blur' },
    { pattern: /^\d+\.\d+(\.\d+)?$/, message: '版本号格式不正确，如：1.0.0', trigger: 'blur' }
  ],
  communicationType: [
    { required: true, message: '请选择通信协议类型', trigger: 'change' }
  ],
  encoding: [
    { required: true, message: '请选择编码格式', trigger: 'change' }
  ],

  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
})

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => !!props.protocolData?.protocolId)

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    productId: undefined,
    productName: '',
    protocolName: '',
    protocolVersion: '',
    communicationType: undefined,
    encoding: undefined,
    status: undefined,
    remark: ''
  })
  formRef.value?.clearValidate()
}

// 获取产品列表（本地写死 + 虚拟请求）
const getProductListData = async () => {
  try {
    await delayRandom()
    productList.value = [
      { id: 'P-1001', name: '水质监测设备' } as ProductInfo,
      { id: 'P-1002', name: '泵站控制器' } as ProductInfo,
      { id: 'P-1003', name: '压力传感器' } as ProductInfo,
      { id: 'P-1004', name: '流量计' } as ProductInfo
    ]
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ElMessage.error('获取产品列表失败')
  }
}

// 处理产品选择变化
const handleProductChange = (productId: string | number) => {
  const selectedProduct = productList.value.find(product => product.id === productId)
  if (selectedProduct) {
    formData.productName = selectedProduct.name
  } else {
    formData.productName = ''
  }
}

// 处理空字符串转换为undefined
const processFormData = (data: any) => {
  const processed = { ...data }
  // 将空字符串转换为undefined，避免select组件显示选择状态
  if (processed.productId === '') processed.productId = undefined
  if (processed.communicationType === '') processed.communicationType = undefined
  if (processed.encoding === '') processed.encoding = undefined
  if (processed.status === '') processed.status = undefined
  return processed
}

// 监听协议数据变化
watch(
  () => props.protocolData,
  (newData) => {
    if (newData) {
      const processedData = processFormData(newData)
      Object.assign(formData, processedData)
    }
  },
  { immediate: true, deep: true }
)

// 监听弹窗显示状态
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue && !props.protocolData) {
      // 新增模式下重置表单
      resetForm()
    }
  }
)

// 组件挂载
onMounted(() => {
  getProductListData()
})

// 提交表单（本地写死 + 虚拟请求）
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    loading.value = true
    await delayRandom()

    const payload = {
      ...formData,
      protocolId: props.protocolData?.protocolId
    }

    if (isEdit.value) {
      ElMessage.success('修改成功')
    } else {
      ElMessage.success('新增成功')
    }

    emit('success', payload)
    handleClose()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  // 只在新增模式下重置表单，编辑模式下保留数据
  if (!isEdit.value) {
    resetForm()
  }
  // 清除验证状态
  formRef.value?.clearValidate()
}
</script>

<style scoped>
</style>